﻿function fileSelected() {
    //重置状态显示
    document.getElementById("msg").innerHTML = "";
    document.getElementById('percentNumber').innerHTML = '';
    document.getElementById("progress").style.width = "0%";
    var file = document.getElementById('fileInput').files[0];
    if (file) {
        var fileSize = 0;
        if (file.size > 1024 * 1024)
            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
        else
            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
        document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
        document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
        document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
    }
}

//上传文件 code:上传的文件类型
function uploadFile(code) {
    var files = document.getElementById('fileInput').files[0];
    if (files == null || files == "") {
        AlertMsg("请选择需要上传的图片");
        return;
    }
    if (files.size > 1024 * 1024 * 5) {
        AlertMsg("上传文件不能大于5M");
        return;
    }
    var fd = new FormData();
    fd.append("fileInput", files);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, true);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", "/RispeSetting/loadFile?code="+code);//修改为自己服务器接口地址
    //xhr.setRequestHeader("Access-Control-Allow-Origin", "*");//需要在IIS里面配置，就可以跨域请求了
    //xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.send(fd);
}

function uploadProgress(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        document.getElementById('percentNumber').innerHTML = percentComplete + '%';
        var jindutiao = document.getElementById("progress");
        jindutiao.style.width = percentComplete + "%";
    }
    else {
        document.getElementById('percentNumber').innerHTML = '不支持进度计算';
    }
}

function uploadComplete(evt) {
    var msg = evt.target.responseText;
    var msgjson = eval("[" + msg + "]");
    if (msgjson[0].code == "上传成功") {
        $("#imgsourse").attr("src", msgjson[0].data);
        AlertMsg("上传成功");
    }
    else {
        AlertMsg("上传失败,请上传正确的文件！");
    }
}

function uploadFailed(evt) {

}

function uploadCanceled(evt) {
    AlertMsg("用户取消了上传或者浏览器删除了连接");
}